#!/usr/bin/python

import json
import random
import uuid
import logging

from locust import HttpUser, task, between

# 商品 ID 列表
products = [
    "0PUK6V6EV0",
    "1YMWWN1N4O",
    "2ZYFJ3GM2N",
    "66VCHSJNUP",
    "6E92ZMYYFZ",
    "9SIQT8TOJO",
    "L9ECAV7KIM",
    "LS4PSXUNUM",
    "OLJCESPC7Z",
    "HQTGWGPNH4",
]

# 加载用户信息
try:
    with open('people.json') as people_file:
        people = json.load(people_file)
except FileNotFoundError:
    logging.error("people.json file not found")
    people = []

class WebsiteUser(HttpUser):
    wait_time = between(0.05, 0.15)

    def add_to_cart(self, user):
        product = random.choice(products)
        self.client.get("/api/products/" + product)
        cart_item = {
            "item": {
                "productId": product,
                "quantity": random.choice([1, 2, 3, 4, 5, 10]),
            },
            "userId": user,
        }
        self.client.post("/api/cart", json=cart_item)

    @task
    def checkout(self):
        try:
            user = str(uuid.uuid1())
            self.add_to_cart(user=user)
            checkout_person = random.choice(people)
            checkout_person["userId"] = user
            self.client.post("/api/checkout", json=checkout_person)
        except:
            logging.error("Error in checkout task")
